package com.zx.mes.hyl.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zx.mes.controller.BaseController;
import com.zx.mes.hyl.entity.*;
import com.zx.mes.hyl.service.*;
import com.zx.mes.hyl.utils.JWTHelper;
import com.zx.mes.response.ObjectRestResponse;
import com.zx.mes.response.TableResultResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2018-07-02
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class TuserController extends BaseController<TuserService,Tuser> {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TroleService roleService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private TresourceService resourceService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private TmenuService menuService;


    @Override
    public ObjectRestResponse<Tuser> add(Tuser tuser) {
        tuser.setId(UUID.randomUUID().toString());
        tuser.setCreatedatetime(new Date());
        return super.add(tuser);
    }

    @Override
    public ObjectRestResponse<Tuser> update(Tuser tuser) {
        tuser.setModifydatetime(new Date());
        return super.update(tuser);
    }

    @Override
    public TableResultResponse<Tuser> list(@RequestParam Map<String, Object> params, Tuser tuser) {
        int page = Integer.valueOf(params.get("page").toString());
        int limit = Integer.valueOf(params.get("limit").toString());

        EntityWrapper<Tuser> wrapper = new EntityWrapper<>();
        if (tuser.getUsername() != null && !"".equals(tuser.getUsername())) {
            wrapper.like("username", tuser.getUsername());
        }
        if (tuser.getCreatedatetimeStart() != null) {
            wrapper.gt("createdatetime", tuser.getCreatedatetimeStart());
        }
        if (tuser.getCreatedatetimeEnd() != null) {
            wrapper.lt("createdatetime", tuser.getCreatedatetimeEnd());
        }

        List<Tuser> list = this.biz.selectPage(new Page(page, limit),wrapper).getRecords();
        TableResultResponse<Tuser> response = null;
        if (list == null) {
            response = new TableResultResponse("无数据", 200, 0L, (long)page, (List)null);
        } else {
            response = new TableResultResponse("分页查询结果", 200, (long)this.biz.selectCount(wrapper), (long)page, list);
        }

        return response;
    }


    @Transactional
    @DeleteMapping("/deleteBatch")
    public ObjectRestResponse<String> deleteBatch(String ids) {
        ObjectRestResponse<String> response = new ObjectRestResponse<>();
        try {
            String[] idArr = ids.split(",");
            biz.deleteBatchIds(Arrays.asList(idArr));
        } catch (Exception e) {
            response.setMessage(e.getMessage());
            response.setStatus(500);
            e.printStackTrace();
        }
        response.setMessage("批量删除成功!");
        return response;
    }

    @GetMapping("/getUserAndRoleAndResourceByUserId")
    public ObjectRestResponse<Tuser> getUserAndRoleAndResourceByUserId(String id){
        // 获取用户
        return new ObjectRestResponse<>().data(biz.getUserAndRoleAndResource(id));
    }

    @PostMapping("/login")
    public ObjectRestResponse<JwtInfo> login(Tuser user){

        ObjectRestResponse<JwtInfo> response = new ObjectRestResponse<>();
        Tuser tuser=biz.selectOne(new EntityWrapper<Tuser>()
                .eq("username",user.getUsername())
                .eq("password",user.getPassword())
        );

        Tuser t= biz.getUserAndRoleAndResource(tuser.getId()).get(0);
        tuser.setRoleList(t.getRoleList());
        JwtInfo jwt = new JwtInfo();
        jwt.setUsername(tuser.getUsername());
        List<Tmenu> tmenuList = null;
        List<Tresource> tresourceList = null;
        Map<String, Tresource> resourceMap = new HashMap<>();
        Map<String, Tmenu> menuMap = new HashMap<>();
        try {
            if (tuser.getRoleList() != null && tuser.getRoleList().size() > 0) {
                for (int i = 0; i < tuser.getRoleList().size(); i++) {
                    Trole trole = tuser.getRoleList().get(i);
                    tmenuList = trole.getMenuList();
                    tresourceList = trole.getResourceList();
                    for (int j = 0; j <tmenuList.size() ; j++) {
                        menuMap.put(tmenuList.get(j).getId(), tmenuList.get(j));
                    }

                    for (int j = 0; j < tresourceList.size() ; j++) {
                        resourceMap.put(tresourceList.get(j).getId(), tresourceList.get(j));
                    }
                }
//                tmenuList = new ArrayList<>((Collection<? extends Tmenu>) menuMap);
//                tresourceList = new ArrayList<>((Collection<? extends Tresource>) resourceMap);

                Set<String> strings = menuMap.keySet();
                for (String str : strings) {
                    tmenuList.add(menuMap.get(str));
                }

                Set<String> strResource = resourceMap.keySet();
                for (String str : strResource) {
                    tresourceList.add(resourceMap.get(str));
                }

            }

            jwt.setId(tuser.getId());
            String token = JWTHelper.generateToken(jwt, "jwt/pri.key", 3600);
            jwt.setMenuList(tmenuList);
            jwt.setResourceList(tresourceList);
            jwt.setResourceList(null);
            jwt.setToken(token);
            response.setData(jwt);
        } catch (Exception e) {
            response.setData(jwt);
            response.setMessage("token获取失败!");
            e.printStackTrace();
        }
        return response;
    }


    public ObjectRestResponse<Tuser> getResourceAndMenuByUser(Tuser tuser) {
        return getAll(tuser);
    }

    /**
     * 根据用户来获取菜单与权限
     * @param tuser
     * @return
     */
    private ObjectRestResponse<Tuser> getAll(Tuser tuser){
        ObjectRestResponse<Tuser> response = new ObjectRestResponse<>();
        /// Tuser user = biz.selectById(tuser.getId());
        List<UserRole> userRoles = userRoleService.selectList(new EntityWrapper<UserRole>().eq("user_id", tuser.getId()));
        List<String> roleIds = new ArrayList<>();
        for (int i = 0; i <userRoles.size() ; i++) {
            roleIds.add(userRoles.get(i).getRoleId());
        }
        /// 获取所有的角色id
        List<RoleResource> roleResources = roleResourceService.selectBatchIds(roleIds);
        Set<String> resourceIds = new HashSet<>();
        for (int i = 0; i <roleResources.size() ; i++) {
            resourceIds.add(roleResources.get(i).getResourceId());
        }
        /// 获取用户权限
        List<Tresource> resourceList = resourceService.selectBatchIds(resourceIds);

        Set<String> menuIds = new HashSet<>();
        List<RoleMenu> roleMenus = roleMenuService.selectBatchIds(roleIds);

        for (int i = 0; i < roleMenus.size(); i++) {
            menuIds.add(roleMenus.get(i).getMenuId());
        }

        List<Tmenu> menuList = menuService.selectBatchIds(menuIds);

        tuser.setResourceList(resourceList);

        tuser.setMenuList(menuList);

        response.setData(tuser);

        return response;
    }


}

